package com.mall.service.impl;

import com.mall.dao.UserMapper;
import com.mall.enums.ResponseEnum;
import com.mall.pojo.User;
import com.mall.service.IUserService;
import com.mall.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;

/**
 * @Author: 黄建
 * @Date: 2020/1/19 22:00
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 注册
     *
     * @param user
     */
    @Override
    public ResponseVo register(User user) {
        //username不能重复
        int countByUsername = userMapper.countByUserName(user.getUsername());
        if (countByUsername > 0) {
            return ResponseVo.error(ResponseEnum.USERNAME_EXIST);
        }

        //email不能重复
        int countByEmail = userMapper.countByEmail(user.getEmail());
        if (countByEmail > 0) {
            return ResponseVo.error(ResponseEnum.EMAIL_EXIST);
        }

        //MD5摘要算法(Spring自带)
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));

        //写入数据库
        int resultCount = userMapper.insertSelective(user);
        if (resultCount == 0) {
            return ResponseVo.error(ResponseEnum.ERROR);
        }
        return ResponseVo.success();
    }

    /**
     *
     */
    @Override
    public ResponseVo<User> login(String username, String password) {

        //获取用户信息
        User user = userMapper.selectByUsername(username);

        if (user == null){
            return ResponseVo.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        //判断密码
        if (!StringUtils.isEmpty(password)){
            if (!user.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))){
                return ResponseVo.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
            }
        }
        user.setPassword(null);
        //返回用户信息
        return ResponseVo.success(user);
    }
}
